package com.ly.mpayment.rest.recharge;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.blacklist.IBlackListService;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.persist.service.mobile.IMobileService;
import com.ly.mpayment.persist.service.provincialinformation.IProvincialInformationService;
import com.ly.mpayment.rest.AbsRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

@Component
@Path("yisai")
public class YiSaiRest extends AbsRest {

	Logger logger = Logger.getLogger(YiSaiRest.class);

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IDownShopProductService productService;

	@Autowired
	IMobileService mobileService;

	@Autowired
	IProvincialInformationService proService;

	@Autowired
	IBlackListService blackListService;

	/**
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("commit")
	@POST
	public String recharge(@RequestBody String data, @Context HttpServletRequest request) {
		logger.info("yisai_commit:"+data);
		return rechargeOrder(data,request,true);
	}

	/**
	 * partnerid 供货商编号 int n 合作伙伴在平台的用户编号(不是用户登录	 * 名).登录平台后可查询
	 * esupordernumber * 平台订单号 string n 平台订单号.
	 * payprice 支付金额 decimal n 支付金额（单位元小数点后保留 3 位）
	 * productid 产品编号 string n 产品编号。登录易赛数据平台产品中心下载
	 * customproid 供货商自定 * 义产品 ID* string n 固定值 none
	 * timestamp 时间戳 string n 时间戳（格式 yyyy/M/d HH:mm:ss）
	 * phonenum 手机号码 string n 充值手机号码
	 * noticeurl 回调地址 string n 订单有结果时可通过回调反馈给平台
	 * sign 签名 string
	 * @param data
	 * @param request
	 * @param isIp
	 * @return
	 */
	public String rechargeOrder(String data,@Context HttpServletRequest request,boolean isIp){
		if (!StringUtils.isBlank(data)) {
			MultiMap multimap = Util.parceString(data);
			DownShopInfo shop = shopService.findByCallUrl(multimap.getString("partnerid"));
			if(shop != null && shop.getUser().getUserstatus() == Config.productStatus[3]){
				final JSONObject out = new JSONObject();
				out.put("result", "t");
				out.put("esupordernumber", multimap.getString("esupordernumber"));
				out.put("provideordernumber", "");
				out.put("time", DateUtils.toLongDate(new Date()));
				out.put("status", 5);
				out.put("finishedtime",DateUtils.toLongDate(new Date()));
				final JSONObject resultdata = new JSONObject();
				resultdata.put("payresult",ResultMessage.userCloseError.getMessage());
				out.put("resultdata",resultdata);
				logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
				return out.toJSONString();
			}

			//查询产品是否正常删除或者禁用的不可以提单
			DownShopProduct downProduct = this.productService.findByYiSai(multimap.getString("productid"),shop.getUser().getUseruuid());
			if (downProduct == null) {
				final JSONObject out = new JSONObject();
				out.put("result", "t");
				out.put("esupordernumber", multimap.getString("esupordernumber"));
				out.put("provideordernumber", "");
				out.put("time", DateUtils.toLongDate(new Date()));
				out.put("status", 5);
				out.put("finishedtime",DateUtils.toLongDate(new Date()));
				final JSONObject resultdata = new JSONObject();
				resultdata.put("payresult",ResultMessage.productDownError.getMessage());
				out.put("resultdata",resultdata);
				logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
				return out.toJSONString();
			}

			if (shop != null ) {
				if(checkIp(shop.getDownshopip(), request,isIp) || shop.getUser().getUseruuid().equals(CookieRedis.get("useruuid"))){
					data = data.substring(0,data.indexOf("sign")-1);
					if(multimap.getString("sign").equals(MD5.md5(URLDecoder.decode(URLDecoder.decode(data)).concat(shop.getUser().getRemark())))){
						String result = chekcParameter(multimap,shop);
						if (result != null) {
							return result;
						}
						Mobile mobile = checkMobile(multimap.getString("phonenum").trim());
						if(mobile == null){
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.phoneNumError.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
						if(blackListService.findPhone(multimap.getString("phonenum")) != null){
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.mobileError.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
						//检查省份是否维护
						//SCDMA	中国移动
						//WCDMA	中国联通
						//CDMA	中国电信
						if(CookieRedis.get("dsable_province") != null && !CookieRedis.get("dsable_province").equals("0")){
							String provinces [] = CookieRedis.get("dsable_province").split(",");
							for(int i = 0 ; i < provinces.length; i ++){
								String pro = provinces[i].contains(Config.opearter[0]) ? Config.opearterName[0] :
											 provinces[i].contains(Config.opearter[1]) ? Config.opearterName[2] :
											 provinces[i].contains(Config.opearter[2]) ? Config.opearterName[1] : "";
								if(mobile.getProvince().equals(provinces[i].split("-")[1]) && mobile.getServiceProvider().equals(pro)){
									final JSONObject out = new JSONObject();
									out.put("result", "t");
									out.put("esupordernumber", multimap.getString("esupordernumber"));
									out.put("provideordernumber", "");
									out.put("time", DateUtils.toLongDate(new Date()));
									out.put("status", 5);
									out.put("finishedtime",DateUtils.toLongDate(new Date()));
									final JSONObject resultdata = new JSONObject();
									resultdata.put("payresult",ResultMessage.buscodeNotError.getMessage());
									out.put("resultdata",resultdata);
									logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
									return out.toJSONString();
								}
							}
						}						//如果是全国则不检查运营商
//							if(CookieRedis.get("nationwide").equals(Config.onOff)){
//								boolean temp = true;
//								for(int i = 0 ;i < Config.opearterName.length;i++){
//									if(Config.opearterName[i].equals(mobile.getServiceProvider()) && downProduct.getOperators().getOperatorname().equals(mobile.getServiceProvider())){
//										temp = false;
//									}
//								}
//								if(temp){
//									return ResultMessage.getFailt(ResultMessage.rechargeNumOperatorError);
//								}
//							}
						//如果产品为全国 则不检查省份
						if(!downProduct.getProvincialInformation().getProvincename().equals(Config.proCity)){
							//检查充值号段与产品号段是否匹配
							if(mobile != null && !mobile.getProvince().equals(downProduct.getProvincialInformation().getProvincename())){
								final JSONObject out = new JSONObject();
								out.put("result", "t");
								out.put("esupordernumber", multimap.getString("esupordernumber"));
								out.put("provideordernumber", "");
								out.put("time", DateUtils.toLongDate(new Date()));
								out.put("status", 5);
								out.put("finishedtime",DateUtils.toLongDate(new Date()));
								final JSONObject resultdata = new JSONObject();
								resultdata.put("payresult",ResultMessage.provinceError.getMessage());
								out.put("resultdata",resultdata);
								logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
								return out.toJSONString();
							}
						}
						//检查省份是否维护
						if(mobile != null && downProduct.getProvincialInformation() != null && !StringUtils.isBlank(mobile.getProvince())
								&& mobile.getProvince().equals(downProduct.getProvincialInformation().getProvincename())){
							if(downProduct.getProvincialInformation().getProvincestatus().equals("0")){
								final JSONObject out = new JSONObject();
								out.put("result", "t");
								out.put("esupordernumber", multimap.getString("esupordernumber"));
								out.put("provideordernumber", "");
								out.put("time", DateUtils.toLongDate(new Date()));
								out.put("status", 5);
								out.put("finishedtime",DateUtils.toLongDate(new Date()));
								final JSONObject resultdata = new JSONObject();
								resultdata.put("payresult",ResultMessage.provinceErrorweihu.getMessage());
								out.put("resultdata",resultdata);
								logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
								return out.toJSONString();
							}
						}

						//检查充值号段是否禁止提单，如果是则不能保存订单
						if(mobile == null || mobile.getState() == Config.mobileState){
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.mobileError.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
						if(!StringUtils.isBlank(downProduct.getCityName()) && !mobile.getCity().equals(downProduct.getCityName())){
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.provinceError.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
						final DownRechargeFlow flow = new DownRechargeFlow();
						Date date = DateUtils.getNowDate();
						flow.setCreatetime(date);
						flow.setDownreqid(multimap.getString("esupordernumber"));
						flow.setUserFlow(shop.getUser());
						flow.setRechargeamount(downProduct.getPrice());
						flow.setDowonphonenum(multimap.getString("phonenum"));
						flow.setOperators(downProduct.getOperators().getOperatoruid());
						flow.setDownnotificationaddress(URLDecoder.decode(URLDecoder.decode(multimap.getString("noticeurl"))));
						if(shop.getUser().getUserstatus() != Config.productStatus[1] || downProduct.getStatus() != Config.productStatus[1]){
							flow.setStatus(Config.status[9] );
							//缓存订单
						}else{
							flow.setStatus(Config.status[5] );
							//订单到达
						}
						flow.setOperatorname(downProduct.getOperators().getOperatorname());
						flow.setBusCode(downProduct.getBusinessType().getBusCode());
						flow.setProvince(mobile.getProvince());
						flow.setCityName(mobile.getCity());
						flow.setCallStatus(Config.callStatus[0]);
						flow.setDownendtimesec(Config.status[3]);
						flow.setDownShopProduct(downProduct);
						flow.setDiscount(downProduct.getDiscount());
						flow.setDiscountAmount(downProduct.getPrice().multiply(downProduct.getDiscount()));
						//重复提交次数 产品默认为1
						flow.setDownreqnum(1);
						flow.setStatusremark(multimap.containsKey("payprice") ? multimap.getString("payprice") : "");
						//查询下游余额
						// 检查余额
						if(CookieRedis.get("checkbalance").equals(Config.onOff)){
							if (shop.getDownshopbalance().compareTo(flow.getDiscountAmount()) == -1) {
								final JSONObject out = new JSONObject();
								out.put("result", "t");
								out.put("esupordernumber", multimap.getString("esupordernumber"));
								out.put("provideordernumber", "");
								out.put("time", DateUtils.toLongDate(new Date()));
								out.put("status", 5);
								out.put("finishedtime",DateUtils.toLongDate(new Date()));
								final JSONObject resultdata = new JSONObject();
								resultdata.put("payresult",ResultMessage.shopAmountError.getMessage());
								out.put("resultdata",resultdata);
								logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
								return out.toJSONString();
							}
						}
						//检查授信额度 如果有授信额度则可以提交订单，如果没有直接返回约不足，如果授信额度满了，直接返回余额不足
						if(flow.getDiscountAmount().compareTo(shop.getDownshopbalance()) == 1
								&& ( flow.getDiscountAmount().compareTo(shop.getCredit()) == 1 )	){
							//return ResultMessage.getFailt(ResultMessage.shopAmountError);
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.shopAmountError.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
						//检查余额消耗。如果余额小于0 则取反大于授信 就不能继续提单
						if(shop.getDownshopbalance().compareTo(BigDecimal.ZERO) == -1 && Math.abs(shop.getDownshopbalance().intValue())
								>= shop.getCredit().intValue()){
							//return ResultMessage.getFailt(ResultMessage.shopAmountError);
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.shopAmountError.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
						try {
							final DownRechargeFlow flowfinal = flowService.addDownrechargeflow(flow, shop);
							if(flowfinal != null){
								//指定订单产品不加入处理队列
								//检查余额 余额不足时 不加入队列处理。
//									if(shop.getDownshopbalance().compareTo(flow.getRechargeamount()) == -1){
//										logger.info("recharge_balance_余额:"+shop.getDownshopbalance());
//									}else{
								if(shop.getUser().getUserstatus() == Config.productStatus[1] && downProduct.getStatus() == Config.productStatus[1]){
									RechargeRest.orderQueue.add(flowfinal);
								}else{
									flow.setRemark("产品或者供货商未启用");
									this.flowService.updateDownrechargeflow(flowfinal);
									logger.info("recharge_缓存订单:"+flowfinal.getDowonphonenum());
								}

//								{
//									"result":"t",
//										"esupordernumber":"01011029641808141515221388150481",
//										"provideordernumber":"01011029641808141515221388150481",
//										"time":"2021-07-26 15:14:55",
//										"status":3,
//										"finishedtime":"2021-07-26 15:16:04",
//								}
//								3 供货商已经受理
//								4 充值成功 最终结果
//								5 充值失败 最终结果
								final JSONObject out = new JSONObject();
								out.put("result", "t");
								out.put("esupordernumber", multimap.getString("esupordernumber"));
								out.put("provideordernumber", flowfinal.getDownorderuuid());
								out.put("time", DateUtils.toLongDate(flowfinal.getCreatetime()));
								out.put("status", 3);
								out.put("finishedtime",DateUtils.toLongDate(flowfinal.getCreatetime()));
								logger.info("returnOrder:"+flowfinal.getDowonphonenum()+","+out.toString());
								return out.toJSONString();
							}else{
								logger.info("failt:"+flow.getDowonphonenum());
								final JSONObject out = new JSONObject();
								out.put("result", "t");
								out.put("esupordernumber", multimap.getString("esupordernumber"));
								out.put("provideordernumber", flowfinal.getDownorderuuid());
								out.put("time", DateUtils.toLongDate(flowfinal.getCreatetime()));
								out.put("status", 5);
								out.put("finishedtime",DateUtils.toLongDate(flowfinal.getCreatetime()));
								final JSONObject resultdata = new JSONObject();
								resultdata.put("payresult",ResultMessage.systemErrorMessageQuery.getMessage());
								out.put("resultdata",resultdata);
								logger.info("returnOrder:"+flowfinal.getDowonphonenum()+","+out.toString());
								return out.toJSONString();
							}
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e.getMessage()+":"+ flow == null ? "flow" : flow.getDowonphonenum());
							//return ResultMessage.getFailt(ResultMessage.systemErrorMessageQuery);
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", "");
							out.put("time", DateUtils.toLongDate(new Date()));
							out.put("status", 5);
							out.put("finishedtime",DateUtils.toLongDate(new Date()));
							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",ResultMessage.systemErrorMessageQuery.getMessage());
							out.put("resultdata",resultdata);
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
					}else{
						logger.info("signError:"+data+","+DateUtils.getNowDateToString());
						final JSONObject out = new JSONObject();
						out.put("result", "t");
						out.put("esupordernumber", multimap.getString("esupordernumber"));
						out.put("provideordernumber", "");
						out.put("time", DateUtils.toLongDate(new Date()));
						out.put("status", 5);
						out.put("finishedtime",DateUtils.toLongDate(new Date()));
						final JSONObject resultdata = new JSONObject();
						resultdata.put("payresult",ResultMessage.signError.getMessage());
						out.put("resultdata",resultdata);
						logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
						return out.toJSONString();
						//return ResultMessage.getFailt(ResultMessage.signError);
					}
				}else{
					final JSONObject out = new JSONObject();
					out.put("result", "t");
					out.put("esupordernumber", multimap.getString("esupordernumber"));
					out.put("provideordernumber", "");
					out.put("time", DateUtils.toLongDate(new Date()));
					out.put("status", 5);
					out.put("finishedtime",DateUtils.toLongDate(new Date()));
					final JSONObject resultdata = new JSONObject();
					resultdata.put("payresult",ResultMessage.shopNotexistErrorIP.getMessage());
					out.put("resultdata",resultdata);
					logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
					return out.toJSONString();
					//return ResultMessage.getFailt(ResultMessage.shopNotexistErrorIP);
				}
			}  else {
				final JSONObject out = new JSONObject();
				out.put("result", "t");
				out.put("esupordernumber", multimap.getString("esupordernumber"));
				out.put("provideordernumber", "");
				out.put("time", DateUtils.toLongDate(new Date()));
				out.put("status", 5);
				out.put("finishedtime",DateUtils.toLongDate(new Date()));
				final JSONObject resultdata = new JSONObject();
				resultdata.put("payresult",ResultMessage.shopNotexistErrorIP.getMessage());
				out.put("resultdata",resultdata);
				logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
				return out.toJSONString();
				//return ResultMessage.getFailt(ResultMessage.shopNotexistErrorIP);
			}
		}
		final JSONObject out = new JSONObject();
		out.put("result", "t");
		out.put("esupordernumber", "");
		out.put("provideordernumber", "");
		out.put("time", DateUtils.toLongDate(new Date()));
		out.put("status", 5);
		out.put("finishedtime",DateUtils.toLongDate(new Date()));
		final JSONObject resultdata = new JSONObject();
		resultdata.put("payresult",ResultMessage.shopParameterError.getMessage());
		out.put("resultdata",resultdata);
		logger.info("returnOrder:"+","+out.toString());
		return out.toJSONString();
		//return ResultMessage.getFailt(ResultMessage.shopParameterError);
	}


	/**
	 * 检查地址
	 * @param phoneNum
	 * @return
	 */
	public Mobile checkMobile(String phoneNum){
		//匹配号码与运营商不符的直接返回错误
		Mobile mobile = mobileService.findPhone(phoneNum.substring(0, 7));
		if (mobile == null) {
			// 查询聚合数据
			net.sf.json.JSONObject city = HttpClient.httpGetJuhe(phoneNum);
			if (city.containsKey("resultcode") && city.getString("resultcode").equals("200")
					&& city.containsKey("result") && !city.getJSONObject("result").isNullObject()) {
				if (city != null && city.getJSONObject("result") != null) {
					// 更新新的电话号段到本地数据库中
					try {
						mobile = new Mobile();
						mobile.setCityCode(city.getJSONObject("result").getString("areacode"));
						mobile.setPhone(phoneNum.substring(0, 7));
						mobile.setProvince(city.getJSONObject("result").getString("province"));
						mobile.setCity(city.getJSONObject("result").getString("city"));
						mobile.setPostCode(city.getJSONObject("result").getString("zip"));
						mobile.setServiceProvider("中国" + city.getJSONObject("result").getString("company"));
						this.mobileService.saveMobile(mobile);
						return mobile;
					}catch (Exception e){
						e.printStackTrace();
						logger.info("异常号码:"+phoneNum);
					}
					return null;
				} else {
					return null;
				}
			}
		}
		return mobile;
	}

	/***
	 * ip检查
	 * @param customerIp
	 * @param request
	 * @param isIp
	 * @return
	 */
	public boolean checkIp(String customerIp, HttpServletRequest request,boolean isIp) {
		if(isIp){
			boolean tempIp = false;
			String ips[] = customerIp.trim().split(",");
			for (String ip : ips) {
				if (ip.equals(IpUtil.getIp(request))) {
					tempIp = true;
					break;
				}
			}
			if (!tempIp) {
				logger.info("checkIp:" + IpUtil.getIp(request));
			}
			return tempIp;
		}
		return true;
	}

	/**
	 * 检查参数的合法性
	 *
	 * @return
	 */
	private String chekcParameter(MultiMap multimap,DownShopInfo downShopInfo) {
		// if (json.getInt("rechargeNum") <= Config.amount) {
		// return ResultMessage.getFailt(ResultMessage.rechargeNumError);
		// }
//		if ( Double.valueOf(json.getString("amount")) <= Config.amount) {
//			return ResultMessage.getFailt(ResultMessage.faceValueError);
//		}

		// if (json.getInt("faceValue") * json.getInt("rechargeNum") !=
		// json.getInt("rechargeSum")) {
		// return ResultMessage.getFailt(ResultMessage.rechargeSumError);
		// }

		// 检查订单是否存在 如果存在则返回
		if (CookieRedis.get("orderOnOff").equals(Config.onOff)) {
			if (flowService.findByShopId(multimap.getString("esupordernumber"),downShopInfo.getUser().getUseruuid()) != null) {
				return ResultMessage.getFailt(ResultMessage.shopNumError);
			}
		}
//		if (StringUtils.isBlank(json.getString("notify"))
//				&& json.getString("notify").startsWith("http")) {
//			return ResultMessage.getFailt(ResultMessage.notifyAddressError);
//		}
		return null;
	}

	/**
	 * partnerid 供货商编号 int n 合作伙伴在平台的用户编号(不是用户登 录名).登录平台后可查询.如 200000
	 * esupordernumber * 订单号 string n 平台订单号.
	 * timestamp 时间戳 string n 时间戳（格式 yyyy/M/dd HH:mm:ss）
	 * sign 签名 string n 参数签名规则请参看相关章节
	 * @param data
	 * @param request
	 * @return
	 */
	@Path("queryOrder")
	@POST
	public synchronized String queryOrder(@RequestBody String data, @Context HttpServletRequest request) {
		logger.info("yisai_down_queryOrder:" + data);
		if (!StringUtils.isBlank(data)) {
			MultiMap multimap = Util.parceString(data);
			// yisai_down_queryOrder:esupordernumber=01012004562203211712392741842106&partnerid=
			// 200578&timestamp=2022%2f3%2f22+10%3a48%3a14&sign=ec98f97cbb2b83c3b39ba95bcbe5385a
			DownShopInfo shop = shopService.findByCallUrl(multimap.getString("partnerid"));
			if (shop != null) {
				if (checkIp(shop.getDownshopip(), request,true)) {
					data = data.substring(0,data.indexOf("sign")-1);
					if (multimap.getString("sign").equals(MD5.md5(URLDecoder.decode(URLDecoder.decode(data)).concat(shop.getUser().getRemark())))) {
						DownRechargeFlow flow = this.flowService.findShopUUIDorder(multimap.getString("esupordernumber"),shop.getUser().getUseruuid());
						if (flow != null) {
//							{
//								"result":"t",
//									"time":"2021-07-26 16:01:18",
//									"esupordernumber":"01011029641808141516427058104481",
//									"provideordernumber":"NWEC100011180814151616925001",
//									"finishedtime":"2021-07-26 16:16:16",
//									"status":4,
//									"resultdata":{
//								"payresult":"充值成功,流水：110103353132107261620470543144"
//							} }
							final JSONObject out = new JSONObject();
							out.put("result", "t");
							out.put("esupordernumber", multimap.getString("esupordernumber"));
							out.put("provideordernumber", flow.getDownorderuuid());
							out.put("time", DateUtils.toLongDate(flow.getCreatetime()));
							out.put("status", flow.getStatus() == 2 ? 4 : flow.getStatus() == 3 ? 5 : 0);
							out.put("finishedtime",DateUtils.toLongDate(flow.getCreatetime()));

							final JSONObject resultdata = new JSONObject();
							resultdata.put("payresult",flow.getRemark());
							out.put("resultdata",resultdata);

							logger.info("returnOrder:"+flow.getDowonphonenum()+","+out.toString());
							return out.toJSONString();
						} else {
							final JSONObject out = new JSONObject();
							out.put("result", "f");
							out.put("errcode", 107);
							out.put("time",DateUtils.toLongDate(new Date()));
							out.put("errmsg",ResultMessage.orderNot.getMessage());
							logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
							return out.toJSONString();
						}
					}
					final JSONObject out = new JSONObject();
					out.put("result", "f");
					out.put("errcode", 199);
					out.put("time",DateUtils.toLongDate(new Date()));
					out.put("errmsg",ResultMessage.searchSignError.getMessage());
					logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
					return out.toJSONString();
				} else {
					final JSONObject out = new JSONObject();
					out.put("result", "f");
					out.put("errcode", 199);
					out.put("time",DateUtils.toLongDate(new Date()));
					out.put("errmsg",ResultMessage.shopNotexistErrorIP.getMessage());
					logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
					return out.toJSONString();
				}
			} else {
				final JSONObject out = new JSONObject();
				out.put("result", "f");
				out.put("errcode", 199);
				out.put("time",DateUtils.toLongDate(new Date()));
				out.put("errmsg",ResultMessage.shopNotexistErrorIP.getMessage());
				logger.info("returnOrder:"+multimap.getString("phonenum")+","+out.toString());
				return out.toJSONString();
			}
		}
		final JSONObject out = new JSONObject();
		out.put("result", "f");
		out.put("errcode", 199);
		out.put("time",DateUtils.toLongDate(new Date()));
		out.put("errmsg",ResultMessage.orderStatusError.getMessage());
		logger.info("returnOrder:"+","+out.toString());
		return out.toJSONString();
	}


	/**
	 * 账户余额查询
	 *
	 * @param data
	 * @return
	 */
	@Path("searchAmount")
	@POST
	public String searchAmount(String data, @Context HttpServletRequest request) {
		logger.info("searchAmount:" + data);
		String result = this.validationParameter(data, "ts", "uid", "sign");
		if (result == null) {
			net.sf.json.JSONObject json = JsonUtils.converToJson(data);
			DownShopInfo shop = shopService.findShopInfoByUuid(json.getString("uid"));
			if (shop != null) {
				if (checkIp(shop.getDownshopip(), request,true)) {
					if (json.getString("sign").equals(getAmountMD5(json, shop))) {
						net.sf.json.JSONObject out = JsonUtils.getJSONOBJCT();
						out.put("balance", shop.getDownshopbalance());
						out.put("uid", shop.getDownshopuuid());
						JSONObject jobOut = new JSONObject();
						jobOut.put("data",out);
						jobOut.put("code","1000");
						jobOut.put("message", "余额查询成功" );
						return jobOut.toJSONString();
					}
					return ResultMessage.getFailt(ResultMessage.amountSignError);
				} else {
					return ResultMessage.getFailt(ResultMessage.shopNotexistErrorIP);
				}
			}
			return ResultMessage.getFailt(ResultMessage.amountParametersError);
		}
		return ResultMessage.getFailt(ResultMessage.amountParametersError);
	}

	private String getAmountMD5(net.sf.json.JSONObject json, DownShopInfo shop) {
		StringBuffer sb = null;
		sb = new StringBuffer();
		sb.append("uid=");
		sb.append(json.getString("uid"));
		sb.append("&ts=");
		sb.append(json.getString("ts"));
		sb.append("&key=");
		sb.append(shop.getDownkey());
		return MD5.md5(sb.toString());
	}

	// 下游回调
	@Path("call")
	@POST
	public String downCall(String data) {
		return "0";
	}


	public static void main(String[] args) {
		 //System.out.println(HttpClient.httpGetJuhe("19521018049"));
//		{"data":"50db456c68ab5e25b1a49cfe3672cf48854bba5b37d2ece6409a69305ae80cbb205b715c40b2f0604f05a765ec739d92a647044ef3
//		a32629b636ab148d4115d19bd71f42dab1c378ed40eb3b6decc9f7db5feaf6a5bbcf205b59610935315054ccadace182936a672b12fc75f22416a2d3ac71bd9b12505
//		5a83cfdbbdc03f9ed7a7707c7297e4308e116afa1a086ee34","key_id":"14","sign":"6783ed63","page":1,"size":10,"search":"17229271111"}
		//String url = "https://haoma.baidu.com/api/v1/search";
//		String url = "https://miao.baidu.com/abdr";
////		JSONObject jsonObject = new JSONObject();
////		//jsonObject.put("search","17229271111");
////		String result = HttpClient.post(url,jsonObject.toString());
		//String str = "customproid=none&esupordernumber=01012000102203151750342154437011&noticeurl=http%3a%2f%2fapi.yisaipay.com%2fProvider%2fOrderResultNotify&partnerid=200578&payprice=9.9500&phonenum=13845536328&productid=PHONE08011514493220&timestamp=2022%2f3%2f15+17%3a50%3a59&sign=1375dfee4971bf4efff0816b176e141a";
		            //customproid=none&esupordernumber=01012000102203151750342154437011&noticeurl=http%3A%2F%2Fapi.yisaipay.com%2FProvider%2FOrderResultNotify&partnerid=200578&payprice=9.9500&phonenum=13845536328&productid=PHONE08011514493220&timestamp=2022%2f3%2f15+17%3a50%3a59&sign=1375dfee4971bf4efff0816b176e141a
		String str = "customproid=none&esupordernumber=01012000102203151750342154437011&noticeurl=http%253A%252F%252Fapi.yisaipay.com%252FProvider%252FOrderResultNotify&partnerid=200578&payprice=9.9500&phonenum=13845536328&productid=PHONE08011514493220&timestamp=2022%252f3%252f15%2B17%253a50%253a59&sign=1375dfee4971bf4efff0816b176e141a";
		 			//customproid=none&esupordernumber=01012000102203151750342154437011&noticeurl=http%253A%252F%252Fapi.yisaipay.com%252FProvider%252FOrderResultNotify&partnerid=200578&payprice=9.9500&phonenum=13845536328&productid=PHONE08011514493220&timestamp=2022%252f3%252f15%2B17%253a50%253a59&sign=1375dfee4971bf4efff0816b176e141a
		System.out.println(URLDecoder.decode(URLDecoder.decode(str)));
		System.out.println(MD5.md5("esupordernumber=01012000102203181348152481148071&finishedtime=2022-03-20 22:47:24&partnerid=200578&provideordernumber=2c922ab97f98a1aa017f9b921dbf3a0a&result=t&resultdata={\"payresult\":\"\"}&status=4&time=2022-03-20 22:47:24&timestamp=2022-03-20 22:47:24"));
//		net.sf.json.JSONObject city = HttpClient.httpGetJuhe("19875381111");
//		if (city.containsKey("resultcode") && city.getString("resultcode").equals("200")
//				&& city.containsKey("result") && !city.getJSONObject("result").isNullObject()) {
//			if (city != null && city.getJSONObject("result") != null) {
//				// 更新新的电话号段到本地数据库中
//			} else {
//			}
//		}
	}
}
